#pragma once

#include <iostream>

#include <unistd.h>
#include <ctime>
#include <memory>
#include <vector>
#include <sstream>
#include "LogMessage.hpp"

namespace my_log
{
    class FormatItem
    {
    public:
        using FPtr = std::shared_ptr<FormatItem>;
        virtual void format(ostream &out, my_log::Log_Msg &log) = 0;
    };

    class TimeFormatItem : public FormatItem
    {
    public:
        TimeFormatItem(std::string time_fmt = "%Y:%m:%d-%H:%M:%S")
            :_time_fmt(time_fmt)
        {

        }
        void format(ostream &out, my_log::Log_Msg &log) override
        {
            time_t c = log._time;
            struct tm t;
            localtime_r(&c, &t);
            char tm[32];
            strftime(tm, sizeof(tm) - 1, _time_fmt.c_str(), &t);
            out << tm;
        }
    
    private:
        std::string _time_fmt;
    };

    class TidFormatItem : public FormatItem
    {
    public:
        void format(ostream &out, my_log::Log_Msg &log) override
        {
            out << log._tid;
        }

    };

    class FileFormatItem : public FormatItem
    {
    public:
        void format(ostream &out, my_log::Log_Msg &log) override
        {
            out << log._filename;
        }

    };

    class LineFormatItem : public FormatItem
    {
    public:
        void format(ostream &out, my_log::Log_Msg &log) override
        {
            out << log._line;
        }
    };

    class LevelFormatItem : public FormatItem
    {
    public:
        void format(ostream &out, my_log::Log_Msg &log) override
        {
            out << my_log::LogLevel::ToString(log._logger_level);
        }
    };

    class LoggerNameFormatItem : public FormatItem
    {
    public:
        void format(ostream &out, my_log::Log_Msg &log) override
        {
            out << log._logger_name;
        }
    };

    class MsgFormatItem : public FormatItem
    {
    public:
        void format (ostream &out, my_log::Log_Msg &log) override
        {
            out << log._payload;
        }
    };

    class NLineFormatItem : public FormatItem
    {
    public:
        void format (ostream &out, my_log::Log_Msg &log) override
        {
            out << "\n";
        }
    };

    class TabFormatItem : public FormatItem
    {
    public:
        void format (ostream &out, my_log::Log_Msg &log) override
        {
            out << "\t";
        }
    };

    class StrFormatItem : public FormatItem
    {
    public:
        StrFormatItem(std::string str)
            :_str(str)
        {}

        void format (ostream &out, my_log::Log_Msg &log) override
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    class Formatter
    {
    public:
        using FPtr = std::shared_ptr<FormatItem>;
        using ptr = std::shared_ptr<Formatter>;

        Formatter(std::string pattern = "[%d{%Y:%m:%d-%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n")
            :_pattern(pattern)
        {
            if (ParseString() == false)
            {
                std::cout << "格式化失败， 请输入正确的格式化字符串" << std::endl;
            }
        }

        void _format(ostream &out, my_log::Log_Msg &log)
        {
            for (auto &it : _items)
            {
                it->format(out, log);
            }
        }

        std::string format(my_log::Log_Msg &log)
        {
            stringstream ss;
            _format(ss, log);
            return ss.str();
        }

    private:
        bool ParseString()
        {
            int pos = 0;
            int n = _pattern.size();
            std::vector<std::pair<std::string, std::string>> _fmts;
            std::string key;
            std::string val;

            while (pos < n)
            {
                if (_pattern[pos] != '%') 
                {
                    val.push_back(_pattern[pos]);
                    pos++;
                    continue;
                }

                if (pos + 1 < n && _pattern[pos + 1] == '%')  //有两个连续的%
                {
                    val.push_back('%');
                    pos += 2;
                    continue;
                }

                if (val.empty() == false)
                {
                    _fmts.push_back({"", val});
                    val.clear();
                }

                pos += 1;
                if (pos == n) 
                {
                    return false;
                }
                key.push_back(_pattern[pos]);
                pos += 1;
                if (pos < n && _pattern[pos] == '{')
                {
                    pos += 1;
                    while (pos < n && _pattern[pos] != '}')
                    {
                        val.push_back(_pattern[pos]);
                        pos++;
                    }
                    if (pos == n && _pattern[pos] != '}')
                    {
                        return false;
                    }
                    pos += 1;
                }

                _fmts.push_back({key, val});
                key.clear();
                val.clear();
            }

            for (auto &e : _fmts)
            {
                _items.push_back(CreateItem(e.first, e.second));   
            }
            return true;
        }

        FormatItem::FPtr CreateItem(std::string &key, std::string &val)
        {
            if (key == "d") return std::make_shared<TimeFormatItem>(val);
            if (key == "t") return std::make_shared<TidFormatItem>();
            if (key == "f") return std::make_shared<FileFormatItem>();  
            if (key == "l") return std::make_shared<LineFormatItem>();
            if (key == "c") return std::make_shared<LoggerNameFormatItem>();
            if (key == "p") return std::make_shared<LevelFormatItem>();
            if (key == "m") return std::make_shared<MsgFormatItem>();
            if (key == "T") return std::make_shared<TabFormatItem>();
            if (key == "n") return std::make_shared<NLineFormatItem>();
            if (key.empty()) return std::make_shared<StrFormatItem>(val);
            std::cout << "没有相应的字符串" << std::endl;
            abort();
        }

    private:
        std::string _pattern;
        std::vector<FormatItem::FPtr> _items;  //保存格式化项目指针
    
    public:
    
        static void Test()
        {
            my_log::Log_Msg msg(__FILE__, __LINE__, "root_logger", my_log::LogLevel::level::DEBUG, "nihao");
            Formatter fmt;
            std::string ret = fmt.format(msg);
            std::cout << ret << std::endl;
        }
    
    };

}

